import { reqDetailList, } from '../../../../../pages/api/goods'
import { reqAddCart, reqCartList } from '../../../../../pages/api/cart'
//导入创建的仓库
import { userBehaviors } from '../../../../../behaviors/userBehaviors'
Page({
  behaviors: [userBehaviors],
  // 页面的初始数据
  data: {
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    buyNow: 0
  },

  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyNow: 1
    })
  },
  async getDetail() {
    const { data: goodsInfo } = await reqDetailList(this.goodsId)

    this.setData({
      goodsInfo
    })
  },
  previewImage() {
    console.log('查看图片');
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },

  onLoad(options) {
    this.goodsId = options.goodsId
    this.getDetail()
    this.getCartCount()
  },
  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    this.setData({
      count: Number(event.detail)
    })
  },

  //确认提交按钮
  async handlerSubmit() {
    const { token, count, blessing, buyNow } = this.data
    // 获取商品的Id
    const goodsId = this.goodsId

    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    // buyNow === 0 加入购物车
    if (buyNow === 0) {
      const res = await reqAddCart({ goodsId, count, blessing })
      if (res.code === 200) {
        wx.showToast({
          title: '加入购物车成功',
        })
        this.getCartCount()
        this.setData({
          show: false
        })
      }
    } else {
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }
  },
  // 计算购物车购买数量
  async getCartCount() {
    if (!this.data.token) return
    const res = await reqCartList()
    if (res.data.length !== 0) {
      let allCount = 0
      res.data.forEach((item) => {
        allCount += item.count
      })
      this.setData({
        // 隐式类型转换
        allCount: (allCount > 99 ? '99+' : allCount) + ''
      })
    }
  }
})
